package com.itboye.sunsunhome.www.aq;

import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.NumberPicker;
import android.widget.TimePicker;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 赵武 on 2015/3/3.
 */
public class CustomTimePickerDialog extends TimePickerDialog {
	private final static int TIME_PICKER_INTERVAL = 10;
	private TimePicker timePicker;
	private final OnTimeSetListener callback;

	public CustomTimePickerDialog(Context context, OnTimeSetListener callBack,
								  int hourOfDay, int minute, boolean is24HourView, CharSequence titleText) {
		super(context, callBack, hourOfDay, minute / TIME_PICKER_INTERVAL, is24HourView);
		this.callback = callBack;
		this.setButton(BUTTON_NEGATIVE, "确定", this);
		this.setButton(BUTTON_POSITIVE, "取消", this);
		this.setTitle(titleText);
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (which == BUTTON_NEGATIVE) {
			if (callback != null && timePicker != null) {
				timePicker.clearFocus();
				callback.onTimeSet(timePicker, timePicker.getCurrentHour(),
						timePicker.getCurrentMinute() * TIME_PICKER_INTERVAL);
			}
		}
	}

	@Override
	protected void onStop() {
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		try {
			Class<?> classForid = Class.forName("com.android.internal.R$id");
			Field timePickerField = classForid.getField("timePicker");
			this.timePicker = (TimePicker) findViewById(timePickerField.getInt(null));
			Field field = classForid.getField("minute");
			NumberPicker mMinuteSpinner = (NumberPicker) timePicker.findViewById(field.getInt(null));
			mMinuteSpinner.setMinValue(0);
			mMinuteSpinner.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
			List<String> displayedValues = new ArrayList<String>();
			for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
				displayedValues.add(String.format("%02d", i));
			}
			mMinuteSpinner.setDisplayedValues(displayedValues.toArray(new String[0]));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
